package com.gxa.learning.portal.controller;

import com.gxa.learning.core.common.ExceptionCode;
import com.gxa.learning.core.common.JsonResult;
import com.gxa.learning.core.exception.BusinessException;
import com.gxa.learning.core.pojo.User;
import com.gxa.learning.core.util.MD5Util;
import com.gxa.learning.portal.service.MessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/myPage")
@Api( tags = "我—主页接口")
public class MyPageController {
    /**
     * 设置token前缀,防止被黑客抓包得到token
     */


    @Autowired
    MessageService messageService;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/logout")
    @ApiOperation("用户退出登录的方法")
    public Map LogOut(String phone) throws BusinessException {
        messageService.logOut(phone);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("退出登录成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/updatepwd")
    @ApiOperation("用户修改密码的操作")
    public Map updatePwd(Long userId, String oldPassword, String newPassword, String confirmPassword) throws BusinessException {

        User user = messageService.selectById(userId);
        //如果老密码输入正确才进行下面的操作，否则抛异常

            //获取盐
            String salt = user.getSalt();
            //获取真正的旧密码
            String oldPwd=user.getPassword();
            //获取真正输入的密码
            String newPwd=MD5Util.encode(oldPassword+salt);
            //要求输入的两次新密码要一致,否则抛异常
            if (oldPwd.equals(newPwd)){
                //如果新密码和确认密码一致，可以修改
                if (newPassword.equals(confirmPassword)) {
                    user.setPassword(MD5Util.encode(newPassword+salt));
                    messageService.updateById(user);
                } else {
                    throw new BusinessException(ExceptionCode.NO_REPEDPWD);
                }
            }else {
                throw new BusinessException(ExceptionCode.ERORR_PWD);
            }



        ////////
        // 生成给前端返回的数据
        JsonResult jsonResult = new JsonResult();
        // 设置返回的数据
        jsonResult.setCode("1");
        jsonResult.setMsg("修改成功");
        // 返回给前端
        return jsonResult.getDataMap();
    }

    @PostMapping("/getMyMessage")
    @ApiOperation("获取个人信息")
    public Map getMyMessage(Long id){
        User user = messageService.selectById(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setData(user);
        jsonResult.setCode("1");
        return jsonResult.getDataMap();
    }
}
